package net.caixiaomi.info.ui.football;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baidu.mobstat.StatService;
import com.google.gson.reflect.TypeToken;

import net.caixiaomi.info.R;
import net.caixiaomi.info.WebViewActivity;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.base.quickadapter.entity.MultiItemEntity;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.interfaces.PlayFootballItemChangeListener;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.ElementCellModel;
import net.caixiaomi.info.model.MatchItem;
import net.caixiaomi.info.model.MatchPlaysList;
import net.caixiaomi.info.model.PlayFootballItem;
import net.caixiaomi.info.model.TakeOrderPreCalculatePriceModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.dialog.BlendDialogFragment;
import net.caixiaomi.info.ui.dialog.FootballSeriesDialogFragment;
import net.caixiaomi.info.ui.dialog.HalfAndAllDialogFragment;
import net.caixiaomi.info.ui.dialog.ScoreDialogFragment;
import net.caixiaomi.info.ui.dialog.TrebleDialogFragment;
import net.caixiaomi.info.ui.login.LoginActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;


/**
 * 足球确认订单页
 */

public class FootballTakeOrderActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener, PlayFootballItemChangeListener, View.OnClickListener {
    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;

    @BindView(android.R.id.list)
    RecyclerView mListView;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    //总共场次
    @BindView(R.id.total)
    TextView mTotalNum;
    //串关
    @BindView(R.id.series)
    TextView mSeries;

    @BindView(R.id.treble)
    TextView mTreble;

    @BindView(R.id.total_price)
    TextView mTotalPrice;
    private int mType = Constants.TYPE_VICTORY_AND_DEFEAT;
    private String mLotteryClassifyId = "";
    private String mPlayClassifyId = "";
    private FootballTakeOrderAdapter mAdapter;
    private int mTrebleNum = 5;//倍数
    private List<MatchItem> mSeriesList = new ArrayList<>();
    private View mBtnSelected;

    private int mMaxDan = 0;
    private int mCurrentSelectCount = 0;
    private long mTakeOrderMinTime = Long.MAX_VALUE;
    private int mCurrentClickItemPosition = -1;
    private boolean mCanTakeOrder = true;//在计算价钱时，记录是否可以购买

    private String mNoEntryMessage="";  //正常情况，message不为空则认为是钱不够，不能跳转到下一个页面

    @OnClick(R.id.btn_done)
    void toDone() {
        try {

            String token = CommonApp.getToken();
            if (TextUtils.isEmpty(token)) {
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                return;
            }

            if (!mBtnSelected.isSelected()) {
                ToastUtil.s(R.string.C_LOTTERY_SERVICE_PROTOCOL_TIP);
                return;
            }

            if (!TextUtils.isEmpty(mNoEntryMessage)) {
                ToastUtil.s(mNoEntryMessage);
                return;
            }

            if (mSeriesList.isEmpty()) {
                return;
            }

            if (!mCanTakeOrder) {
                return;
            }

            AppHelper.sendStatistics("touzhuqdzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});

            JSONObject params = getParam();

//            Intent intent = new Intent(this, PaymentActivity.class);
//            intent.putExtra("data", params.toString());
//            startActivity(intent);


            RequestService requestService = RetrofitManage.getInstance().getRequestService();
            Call<BaseCallModel> confirm = requestService.saveBetInfo(params);
            confirm.enqueue(new ResponseCallback<BaseCallModel>() {
                @Override
                public void onSuccess(BaseCallModel data) {
                    String patToken= (String) data.data;
                    Intent intent = new Intent(FootballTakeOrderActivity.this, PaymentActivity.class);
                    intent.putExtra("payToken", patToken);
                    intent.putExtra("type",mType);
                    startActivity(intent);

                }

                @Override
                public void onFail(ResponseError error) {

                }

                @Override
                public void onError() {

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //选择串关
    @OnClick(R.id.series)
    void toSeries() {
        try {
            if (mSeriesList.isEmpty()) {
                return;
            }
            AppHelper.sendStatistics("chuanguanzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
            String strData = JSON.toJSONString(mSeriesList);
            FootballSeriesDialogFragment trebleDialog = new FootballSeriesDialogFragment();
            Bundle bundle = new Bundle();
            bundle.putString("data", strData);
            trebleDialog.setArguments(bundle);
            trebleDialog.show(getSupportFragmentManager(), FootballSeriesDialogFragment.class.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //选择倍数
    @OnClick(R.id.treble)
    void toTreble() {
        AppHelper.sendStatistics("beishuzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
        TrebleDialogFragment trebleDialog = new TrebleDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("treble", mTrebleNum);
        trebleDialog.setArguments(bundle);
        trebleDialog.show(getSupportFragmentManager(), TrebleDialogFragment.class.getName());
    }


    @Override
    protected int layout() {
        return R.layout.act_football_take_order;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            String type = getIntent().getStringExtra("playType");
            mLotteryClassifyId = getIntent().getStringExtra("lotteryClassifyId");
            mPlayClassifyId = getIntent().getStringExtra("playClassifyId");

            if (!TextUtils.isEmpty(type)) {
                mType = Integer.valueOf(type);
            }
            mProgress.setVisibility(View.GONE);
            String strData = getIntent().getStringExtra("data");
            List<MultiItemEntity> data = JSON.parseObject(strData, new TypeToken<List<PlayFootballItem>>() {
            }.getType());
            Collections.sort(data, new Comparator<MultiItemEntity>() {
                @Override
                public int compare(MultiItemEntity o1, MultiItemEntity o2) {
                    PlayFootballItem model1 = (PlayFootballItem) o1;
                    PlayFootballItem model2 = (PlayFootballItem) o2;

                    return Long.valueOf(model1.getPlayCode()) > Long.valueOf(model2.getPlayCode()) ? 1 : -1;
                }
            });
            mRefresh.setEnableRefresh(false);
            View footerView = LayoutInflater.from(CommonApp.getInstance()).inflate(R.layout.view_service_protocol, null);
            mBtnSelected = footerView.findViewById(R.id.btn_selected);
            mBtnSelected.setOnClickListener(this);
            mBtnSelected.setSelected(true);
            footerView.findViewById(R.id.btn_protocol).setOnClickListener(this);

            mListView.setLayoutManager(new LinearLayoutManager(this));
            mAdapter = new FootballTakeOrderAdapter(mType, data);
            mAdapter.addFooterView(footerView);
            mAdapter.openLoadAnimation();
            mAdapter.setOnItemChildClickListener(this);
            mAdapter.setListener(this);
            mListView.setAdapter(mAdapter);
            mAdapter.setEnableLoadMore(false);
            recreateSeries();
            updateTreble();
            loadData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.edit, menu);
//        MenuItem menuItem = menu.findItem(R.id.btn_edit);
//        menuItem.setTitle(R.string.C_BOLD);
//        return true;
//    }


    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.edit, menu);
        MenuItem item = menu.findItem(R.id.btn_edit);
        TextView mFilterMenu=null;
        if (mFilterMenu == null) {
            mFilterMenu = new TextView(this);
            mFilterMenu.setGravity(Gravity.CENTER_VERTICAL);
            mFilterMenu.setPadding(0, (int) getResources().getDimension(R.dimen.padding_8), (int) getResources().getDimension(R.dimen.padding_12), (int) getResources().getDimension(R.dimen.padding_8));
            mFilterMenu.setCompoundDrawablePadding((int) getResources().getDimension(R.dimen.padding_5));
            mFilterMenu.setText(getResources().getString(R.string.C_BOLD));
            mFilterMenu.setTextColor(getResources().getColor(R.color.bar_background_text_color));
            mFilterMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(Constants.BASE_H5_URL).append(getString(R.string.H5_DAN_EXPLAIN));
                    String url = stringBuilder.toString();
                    Intent intent = new Intent(FootballTakeOrderActivity.this, WebViewActivity.class);
                    intent.putExtra("url", url);
                    startActivity(intent);
                }
            });
        }
        item.setActionView(mFilterMenu);

        return true;
    }



    public boolean onPrepareOptionsMenu(Menu menu) {
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.btn_edit:
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(Constants.BASE_H5_URL).append(getString(R.string.H5_DAN_EXPLAIN));
                String url = stringBuilder.toString();
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
                break;

        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this,"touzhuqueren-view");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this,"touzhuqueren-view");
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_TREBLE://选择倍数
                    mTrebleNum = Integer.valueOf(event.getMessage());
                    AppHelper.sendStatistics("bsqdzc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
                    updateTreble();
                    loadData();
                    break;
                case EventWhat.EVENT_SERIES://选择串关
                    mSeriesList = JSON.parseObject(event.getMessage(), new TypeToken<List<MatchItem>>() {
                    }.getType());
                    updateDanSeries(mSeriesList);
                    mAdapter.notifyDataSetChanged();
                    AppHelper.sendStatistics("cgzhongleizc", new String[]{getString(R.string.C_SERIES)}, new String[]{mSeries.getText().toString().trim()});
                    loadData();
                    break;
                case EventWhat.EVENT_PAYMENT://支付
                    finish();
                    break;
                case EventWhat.EVENT_FOOTBALL_SELECT_DONE://投注前选完
                    handleSelectItem(event.getMessage());
                    break;
                case EventWhat.EVENT_LOGIN:
                    toDone();
                    break;

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void updateTreble() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getString(R.string.C_TREBLE)).append("    ").append(mTrebleNum).append(getString(R.string.C_TREBLE_CHAT));
        mTreble.setText(stringBuilder);
    }

    private void updateDanSeries(List<MatchItem> series) {
        List<MatchItem> selectd = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getString(R.string.C_SERIES)).append("    ");
        for (MatchItem item : series) {
            if (item.isSelect()) {
                selectd.add(item);
                stringBuilder.append(item.getLeagueAddr()).append(",");
            }
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        mSeries.setText(stringBuilder);

        resetDan();

        //先取最后一个，判断是否可以设置胆，再取第一个判断设置几个胆
        MatchItem first = null;
        MatchItem last = null;
        boolean canSelectDan = true;
        if (!selectd.isEmpty()) {
            if (selectd.size() > 1) {
                first = selectd.get(0);
                last = selectd.get(selectd.size() - 1);
            } else {
                first = selectd.get(0);
                last = selectd.get(0);
            }
        }

        if (last != null) {
            int num = Integer.valueOf(last.getLeagueId().substring(0, 1));
            if (num >= mCurrentSelectCount) {
                canSelectDan = false;
                mMaxDan = 0;
            }
        }
        if (canSelectDan && first != null) {
            int num = Integer.valueOf(first.getLeagueId().substring(0, 1));
            if (num < mCurrentSelectCount) {
                mMaxDan = num - 1;
            }
        }


        mAdapter.setMaxDan(mMaxDan);
    }

    /**
     * getBetInfo & saveBetInfo 统一参数
     */
    private JSONObject getParam() {
        StringBuilder stringBuilder = new StringBuilder();
        for (MatchItem item : mSeriesList) {
            if (item.isSelect()) {
                stringBuilder.append(item.getLeagueId()).append(",");
            }
        }
        if (!TextUtils.isEmpty(stringBuilder)) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        String betType = stringBuilder.toString();
        JSONArray matchBetPlays = new JSONArray();
        Iterator<MultiItemEntity> iterator = mAdapter.getData().iterator();
        while (iterator.hasNext()) {
            PlayFootballItem model = (PlayFootballItem) iterator.next();
            List<ElementCellModel> selectCells = model.getSelectCell();
            JSONArray matchBetCells = new JSONArray();

            for (MatchPlaysList matchPlaysList : model.getMatchPlays()) {
                JSONObject matchBetCell = new JSONObject();

                JSONArray betCells = new JSONArray();

                int playType = Integer.valueOf(matchPlaysList.getPlayType());
                boolean hasSelect = false;
                for (ElementCellModel cellModel : selectCells) {
                    if (playType == Integer.valueOf(cellModel.getPlayType())) {
                        betCells.add(cellModel);
                        hasSelect = true;
                    }
                }
                if (!hasSelect) {
                    continue;
                }

                matchBetCell.put("playType", matchPlaysList.getPlayType());
                matchBetCell.put("betCells", betCells);
                matchBetCell.put("single", matchPlaysList.getSingle());
                matchBetCell.put("fixedOdds", matchPlaysList.getFixedOdds());
                matchBetCells.add(matchBetCell);
            }

            if (mType == 7) {//二选一玩法
                JSONArray newMatchBetCells = new JSONArray();
                newMatchBetCells.addAll(matchBetCells);
                matchBetCells.clear();
                for (int matchBetCellIndex = 0; matchBetCellIndex < newMatchBetCells.size(); matchBetCellIndex++) {
                    JSONObject oldMatchBetCell = newMatchBetCells.getJSONObject(matchBetCellIndex);
                    JSONArray oldBetCells = oldMatchBetCell.getJSONArray("betCells");
                    for (int index = 0; index < oldBetCells.size(); index++) {
                        JSONObject matchBetCell = new JSONObject();
                        JSONArray betCells = new JSONArray();
                        ElementCellModel cellModel = oldBetCells.getObject(index, ElementCellModel.class);
                        ElementCellModel newCellModel = new ElementCellModel();
                        if (TextUtils.equals(cellModel.getCellCode(), "30")) {
                            matchBetCell.put("playType", "2");
                            newCellModel.setCellCode("0");
                            newCellModel.setCellName(getString(R.string.C_GUEST_WIN));
                        } else if (TextUtils.equals(cellModel.getCellCode(), "31")) {
                            matchBetCell.put("playType", "2");
                            newCellModel.setCellCode("3");
                            newCellModel.setCellName(getString(R.string.C_HOST_WIN));
                        } else if (TextUtils.equals(cellModel.getCellCode(), "32")) {
                            matchBetCell.put("playType", "1");
                            newCellModel.setCellCode("3");
                            newCellModel.setCellName(getString(R.string.C_CONCEDE) + getString(R.string.C_HOST_WIN));
                        } else if (TextUtils.equals(cellModel.getCellCode(), "33")) {
                            matchBetCell.put("playType", "1");
                            newCellModel.setCellCode("0");
                            newCellModel.setCellName(getString(R.string.C_CONCEDE) + getString(R.string.C_GUEST_WIN));
                        }

                        newCellModel.setCellOdds(cellModel.getCellOdds());
                        betCells.add(newCellModel);
                        matchBetCell.put("betCells", betCells);
                        matchBetCell.put("single", oldMatchBetCell.getString("single"));
                        matchBetCell.put("fixedOdds", oldMatchBetCell.getString("fixedOdds"));
                        matchBetCells.add(matchBetCell);
                    }
                }
            }

            if (!matchBetCells.isEmpty()) {
                JSONObject matchBetPlay = new JSONObject();
                stringBuilder.setLength(0);
                stringBuilder.append(model.getHomeTeamName()).append("VS").append(model.getVisitingTeamName());
                matchBetPlay.put("changci", model.getChangci());
                matchBetPlay.put("changciId", model.getChangciId());
                matchBetPlay.put("isDan", String.valueOf(model.isBlod() ? 1 : 0));
                matchBetPlay.put("lotteryClassifyId", String.valueOf(mLotteryClassifyId));
                matchBetPlay.put("lotteryPlayClassifyId", String.valueOf(mPlayClassifyId));
                matchBetPlay.put("matchId", model.getMatchId());
                matchBetPlay.put("matchTeam", stringBuilder.toString());
                matchBetPlay.put("matchTime", model.getMatchTime());
                matchBetPlay.put("playCode", model.getPlayCode());
                matchBetPlay.put("matchBetCells", matchBetCells);

                matchBetPlays.add(matchBetPlay);
            }
        }

        JSONObject params = new JSONObject();

        params.put("betType", betType);
        params.put("lotteryClassifyId", mLotteryClassifyId);
        params.put("lotteryPlayClassifyId", mPlayClassifyId);
        params.put("playType", String.valueOf(mType == 7 ? 6 : mType));
        params.put("times", String.valueOf(mTrebleNum));
        params.put("matchBetPlays", matchBetPlays);
        return params;
    }

    private void loadData() {
        try {
            if (mSeriesList.isEmpty()) {
                return;
            }

            JSONObject params = getParam();

            RequestService requestService = RetrofitManage.getInstance().getRequestService();
            Call<BaseCallModel<TakeOrderPreCalculatePriceModel>> betInfo = requestService.getBetInfo(params);
            betInfo.enqueue(new ResponseCallback<BaseCallModel<TakeOrderPreCalculatePriceModel>>(this) {
                @Override
                public void onSuccess(BaseCallModel<TakeOrderPreCalculatePriceModel> data) {
                    TakeOrderPreCalculatePriceModel model = data.data;
                    updatePrice(model);
                    mNoEntryMessage=data.msg;
                    if (!TextUtils.isEmpty(data.msg)) {
                        ToastUtil.s(data.msg);
                    }
                }

                @Override
                public void onFail(ResponseError error) {
                    mCanTakeOrder = false;
                    if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                        ToastUtil.s(error.getMessage());
                    }
                }

                @Override
                public void onError() {
                    mCanTakeOrder = false;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前选中的item
     */
    private List<MultiItemEntity> getCurrentSelectedItem() {
        mTakeOrderMinTime = Long.MAX_VALUE;
        List<MultiItemEntity> selected = new ArrayList<>();
        Iterator<MultiItemEntity> iterator = mAdapter.getData().iterator();
        while (iterator.hasNext()) {
            PlayFootballItem model = (PlayFootballItem) iterator.next();
            List<ElementCellModel> selectCell = model.getSelectCell();
            boolean hasSelected = selectCell != null && !selectCell.isEmpty();

            if (hasSelected) {
                selected.add(model);
                mTakeOrderMinTime = Math.min(mTakeOrderMinTime, Long.valueOf(model.getBetEndTime()));
            }
        }

        return selected;
    }

    /**
     * 是否支持单关
     */
    private boolean mIsSupportSingle = true;
    /**
     * 是否有总进球玩法
     */
    private boolean mHasAllGoalsType = false;
    /**
     * 是否有比分、半全场玩法
     */
    private boolean mHasScoreOrHaflAllType = false;

    private void recreateSeries() {
        try {
            List<MultiItemEntity> selected = getCurrentSelectedItem();
            if (mCurrentSelectCount != selected.size() || mType == Constants.TYPE_BLEND) {
                mSeriesList.clear();
                mIsSupportSingle = true;
                mHasAllGoalsType = false;
                mHasScoreOrHaflAllType = false;
                if (!selected.isEmpty()) {
                    checkSupportSingle(selected);

                    if (mIsSupportSingle) {
                        MatchItem matchItem = new MatchItem();
                        matchItem.setLeagueAddr(getString(R.string.C_SINGLE_SERIES));
                        matchItem.setLeagueId("11");
                        mSeriesList.add(matchItem);
                    }
                    int max = 8;
                    if (mHasAllGoalsType) {
                        max = 6;
                    }
                    if (mHasScoreOrHaflAllType) {
                        max = 4;
                    }

                    if (max > selected.size()) {
                        max = selected.size();
                    }
                    for (int index = 2; index <= max; index++) {
                        MatchItem matchItem = new MatchItem();
                        matchItem.setLeagueAddr(index + getString(R.string.C_BUNCH) + "1");
                        matchItem.setLeagueId(index + "1");
                        mSeriesList.add(matchItem);
                    }
                    if (!mSeriesList.isEmpty()) {
                        mSeriesList.get(mSeriesList.size() - 1).setSelect(true);
                    } else {
                        ToastUtil.s(R.string.C_FOOTBALL_SELECT_TIP);
                    }
                }
                mCurrentSelectCount = selected.size();
                updateDanSeries(mSeriesList);
            }

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            String format = selected.isEmpty() ? "" : sdf.format(new Date(mTakeOrderMinTime * 1000));
            String text = getString(R.string.C_TAKE_ORDER_INFO, selected.size(), format);
            SpannableString spannableString = new SpannableString(text);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.orange_primary)), text.length() - format.length(), text.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mTotalNum.setText(spannableString);
            if (mSeriesList.isEmpty()) {
                updatePrice(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查是否支持单关
     */
    private void checkSupportSingle(List<MultiItemEntity> selected) {
        Iterator<MultiItemEntity> iterator = selected.iterator();
        while (iterator.hasNext()) {
            PlayFootballItem model = (PlayFootballItem) iterator.next();
            List<MatchPlaysList> matchPlays = model.getMatchPlays();
            List<ElementCellModel> selectCell = model.getSelectCell();
            for (MatchPlaysList matchPlaysList : matchPlays) {
                for (ElementCellModel cellModel : selectCell) {
                    if (TextUtils.equals(cellModel.getPlayType(), matchPlaysList.getPlayType())) {
                        if (TextUtils.equals(matchPlaysList.getSingle(), "0")) {
                            mIsSupportSingle = false;
                        }
                        int playType = Integer.valueOf(cellModel.getPlayType());
                        if (playType == Constants.TYPE_ALL_GOALS) {
                            mHasAllGoalsType = true;
                        } else if (playType == Constants.TYPE_SCORE || playType == Constants.TYPE_HALF_AND_ALL) {
                            mHasScoreOrHaflAllType = true;
                        }
                    }

                }
            }
        }
    }

    /**
     * 重置胆
     */
    private void resetDan() {
        Iterator<MultiItemEntity> iterator = mAdapter.getData().iterator();
        while (iterator.hasNext()) {
            PlayFootballItem model = (PlayFootballItem) iterator.next();
            model.setBlod(false);
        }
    }

    private void updatePrice(TakeOrderPreCalculatePriceModel model) {
        try {
            String needPrice = "0.00";
            String minBonus = "0.00";
            String maxBonus = "0.00";
            String betNum = "0";
            String times = String.valueOf(mTrebleNum);
            if (model != null) {
                needPrice = model.getMoney();
                minBonus = model.getMinBonus();
                maxBonus = model.getMaxBonus();
                betNum = model.getBetNum();
                times = model.getTimes();
            }

            mCanTakeOrder = new BigDecimal(model.getMaxLotteryMoney()).compareTo(new BigDecimal("20000")) != 1 && (new BigDecimal(betNum).compareTo(new BigDecimal("10000")) != 1 && new BigDecimal(betNum).compareTo(new BigDecimal("0")) == 1);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(getString(R.string.C_MONEY_CHAT)).append(needPrice);
            String price = stringBuilder.toString();
            stringBuilder.setLength(0);
            stringBuilder.append(minBonus).append(" - ").append(maxBonus).append(getString(R.string.C_MONEY));
            String prePrice = stringBuilder.toString();
            String text = getString(R.string.C_TAKE_ORDER_PRE_PRICE, betNum, times, price, prePrice);
            SpannableString spannableString = new SpannableString(text);
            int start = text.indexOf(price);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.orange_primary)), start, start + price.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            start = text.indexOf(prePrice);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.orange_primary)), start, start + prePrice.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mTotalPrice.setText(spannableString);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            PlayFootballItem model = (PlayFootballItem) mAdapter.getData().get(position);
            switch (view.getId()) {
                case R.id.btn_delete:
                    mAdapter.remove(position);
                    recreateSeries();
                    break;
                case R.id.btn_bold:
                    model.setBlod(!model.isBlod());
                    mMaxDan = model.isBlod() ? mMaxDan - 1 : mMaxDan + 1;
                    mAdapter.setMaxDan(mMaxDan);
                    break;
                case R.id.btn_pay:
                    mCurrentClickItemPosition = position;
                    String strData = JSON.toJSONString(model);
                    int playType = Integer.valueOf(model.getPlayType());
                    DialogFragment dialog = null;
                    if (playType == Constants.TYPE_HALF_AND_ALL) {
                        dialog = new HalfAndAllDialogFragment();
                    } else if (playType == Constants.TYPE_SCORE) {
                        dialog = new ScoreDialogFragment();
                    } else if (playType == Constants.TYPE_BLEND) {
                        dialog = new BlendDialogFragment();
                    }

                    Bundle bundle = new Bundle();
                    bundle.putString("data", strData);
                    dialog.setArguments(bundle);
                    dialog.show(getSupportFragmentManager(), dialog.getClass().getName());
                    return;

            }
            loadData();
            mAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleSelectItem(String message) {
        try {
            if (!TextUtils.isEmpty(message) && mCurrentClickItemPosition != -1) {
                PlayFootballItem oldItem = (PlayFootballItem) mAdapter.getData().get(mCurrentClickItemPosition);
                PlayFootballItem newItem = JSON.parseObject(message, new TypeReference<PlayFootballItem>() {
                });
                mCurrentClickItemPosition = -1;
                if (newItem.getSelectCell() != null) {
                    oldItem.setSelectCell(newItem.getSelectCell());
                    oldItem.setMatchPlays(newItem.getMatchPlays());
                }
                onItemChangeListener(oldItem);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean canChange(PlayFootballItem item) {
        return true;
    }

    @Override
    public void onItemChangeListener(PlayFootballItem item) {
        try {
            recreateSeries();
            loadData();
            mAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_selected:
                v.setSelected(!v.isSelected());
                if (!v.isSelected()) {
                    ToastUtil.s(R.string.C_LOTTERY_SERVICE_PROTOCOL_TIP);
                }
                break;
            case R.id.btn_protocol:
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(Constants.BASE_H5_URL).append(getString(R.string.H5_BUY_PROTOCOL));
                String url = stringBuilder.toString();
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
                break;
        }
    }

    private String getTitleFormType() {
        String title = "";
        switch (mType) {
            case Constants.TYPE_VICTORY_AND_DEFEAT:
                title = getString(R.string.C_VICTORY_AND_DEFEAT);
                break;
            case Constants.TYPE_VICTORY_AND_DEFEAT_1:
                title = getString(R.string.C_VICTORY_AND_DEFEAT_1);
                break;
            case Constants.TYPE_ALL_GOALS:
                title = getString(R.string.C_ALL_GOALS);
                break;
            case Constants.TYPE_HALF_AND_ALL:
                title = getString(R.string.C_HALF_AND_ALL);
                break;
            case Constants.TYPE_SCORE:
                title = getString(R.string.C_SCORE);
                break;
            case Constants.TYPE_BLEND:
                title = getString(R.string.C_BLEND);
                break;
            case Constants.TYPE_2_IN_1:
                title = getString(R.string.C_2_IN_1);
                break;
        }
        return title;
    }

    @Override
    public void onBackPressed() {
        AppHelper.sendStatistics("touzhufanhuizc", new String[]{getString(R.string.C_TYPE_OF_LOTTERY)}, new String[]{getTitleFormType()});
        super.onBackPressed();
    }
}
